$(function () {
    marked.setOptions({
        langPrefix: ''
    });

    preview = function setMarkdown(md_text) {
        if (md_text === "") return false;

        // 1. 还原换行
        md_text = md_text.replace(/\\n/g, "\n");

        // 2. 只对相对路径的图片链接添加 /local_files/ 前缀，避免重复添加
        md_text = md_text.replace(/!\[.*?\]\((.*?)\)/g, function(match, p1) {
            if (!p1.startsWith('http') && !p1.startsWith('/local_files/') && !p1.startsWith('file://')) {
                return match.replace(p1, '/local_files/' + p1);
            }
            return match;
        });

        // 3. 对 <source src="..."> 的视频路径做相同处理
        md_text = md_text.replace(/<source\s+src=["'](.*?)["']/g, function(match, path) {
            if (!path.startsWith('http') && !path.startsWith('/local_files/') && !path.startsWith('file://')) {
                return match.replace(path, '/local_files/' + path);
            }
            return match;
        });

        // 4. 转成 HTML
        var md_html = marked(md_text);

        // 5. 给 HTML 加上 base 标签，确保相对路径都从 /local_files/ 开始解析
        const fullHtml = `
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <base href="/local_files/">
    <link rel="stylesheet" href="css/github.css">
    <link rel="stylesheet" href="css/katex.min.css">
    <link rel="stylesheet" href="css/bootstrap.css">
    <style>img{width:100%}</style>
</head>
<body>
    <div class="container" id="preview">
        ${md_html}
    </div>

    <script>
        // 6. 代码高亮
        document.querySelectorAll('pre code').forEach((block) => {
            hljs.highlightBlock(block);
        });

        // 7. 渲染数学公式
        if (typeof renderMathInElement === 'function') {
            renderMathInElement(document.getElementById('preview'), {
                delimiters: [
                    { left: "$$", right: "$$", display: true },
                    { left: "$", right: "$", display: false }
                ]
            });
        }
    </script>
</body>
</html>`;

        // 8. 更新页面内容
        $('#preview').html(md_html);

        // 9. 导出给 Android
        if (window.AndroidInterface && typeof window.AndroidInterface.onHtmlRendered === 'function') {
            window.AndroidInterface.onHtmlRendered(fullHtml);
        }

        // 10. 点击图片事件绑定
        function bindImageClick() {
            const imgs = document.querySelectorAll('.image');
            imgs.forEach(img => {
                img.style.cursor = 'pointer';
                img.addEventListener('click', () => {
                    const src = img.getAttribute('src');
                    if (window.AndroidInterface && src) {
                        window.AndroidInterface.openImageFullScreen(src);
                    }
                });
            });
        }
        bindImageClick();

        function bindFavoriteClick() {
          document.querySelectorAll('.favorite a').forEach(aTag => {
            aTag.addEventListener('click', function (e) {
              e.preventDefault();
              const url = new URL(aTag.href);
              const md5 = url.searchParams.get("md5");
              const pos = url.searchParams.get("pos");
              console.log("点击收藏：", md5, pos); // ✅ 可选调试输出
              if (window.AndroidInterface && window.AndroidInterface.onFavoriteClick) {
                window.AndroidInterface.onFavoriteClick(md5, parseInt(pos));
              }
            });
          });
        }
        bindFavoriteClick();
    };
});
